package cn.com.dstz.admin.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;

import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.Common;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.NumberUtils;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.web.constants.Constants;
import cn.com.dstz.base.action.BaseAction;

/**
 * 查看管理组Action
 * 
 * 1. 管理组新增字段， 允许查看的分组信息
 * 		只能逐级递增，如当前的级别是：3，他只能查看4和5， 不能查看2.
 * 
 * @author 叶装装
 *
 */
public class AdminGroupAct extends BaseAction{
	
	
	public void list( ){
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		
		int level = ActionUtils.getAdminLevel( admin );
		
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "ismanager", 1 );
		
		String sql = "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid and t.ismanager=:ismanager";
		
		if( level > 0 ){
			sql += " and t.level >=:level ";
			valueMap.put( "level", level );
		}
		
		this.responseToJsonObject( this.paginationBySQL( sql, null, valueMap,  null )  );
		
		return;
	}
	
	public void add( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 0 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		int response = 0;
		
		int save = baseService.save( "dstzgroup", DataBaseUtils.getData( new String[]{
				"name"
		}, new Object[]{
				name
		} ), true );
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		if( save > 0 && level == 0){
			int saveGroup = baseService.save( "dstz_group_type", DataBaseUtils.getData( new String[]{
					"groupid", "allowlogin", "ismanager", "level", "isdefault"
			}, new Object[]{
					save, allowlogin, ismanager, this.level,  getIsdefault( )
			} ) );
			// 如果这个保存失败，则删除原来的
			if( saveGroup <= 0 ){
				delete( save );
			}
			
			response = saveGroup;
		}
		
		this.addLog( response, "admingroup", 0, name );
		
		this.ajaxResponse( response > 0 ? 0 : -1 );
		
		return;
		
	}
	
	/**
	 * 转到添加页面
	 * 在转到页面的时候，自动生成一个管理员等级
	 * @return
	 */
	public String toadd( ){
		return "add";
	}
	
	public void edit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 1 );
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );   // 返回错误消息
			return;
		}
		
		int response = 0;
		
		int update = baseService.update( "dstzgroup", DataBaseUtils.getData( new String[]{
				"name"
		}, new Object[]{
				name
		} ), DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		// 只有是系统管理员才进行其他属性的修改
		if( update > 0 && level == 0 ){
			response = baseService.update( "dstz_group_type", DataBaseUtils.getData( new String[]{
					"allowlogin", "ismanager", "level", "isdefault"
			}, new Object[]{
					allowlogin, ismanager, this.level, getIsdefault( )
			} ), DataBaseUtils.getData( new String[]{
					"groupid"
			}, new Object[]{
					id
			} )  );
		}else{
			response = update;
		}
		
		this.addLog( response, "admingroup", 1, "ID：" + id );
		
		this.ajaxResponse( response > 0 ? 0 : -1 ); 
		return;
		
	}
	
	public String toedit( ){
		
		int id = NumberUtils.getInt( getParameter("id"), 0 );
		if( id > 0 ){
			String sql = "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid and t.groupid=:groupid";
			Map< String, Object > data = baseService.queryForMap( sql, DataBaseUtils.getData( new String[]{"groupid"}, new Object[]{id} ) );
			getRequest( ).setAttribute( "data", data );
		}else{
			alertMsg( null );
		}
		
		return "edit";
	}
	
	public void delete( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		// 对系统管理员不进行此判断
		if( level > 0 ){
			String sql = "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid and t.groupid=:groupid";
			Map< String, Object > data = baseService.queryForMap( sql, DataBaseUtils.getData( new String[]{"groupid"}, new Object[]{id} ) );
			
			if( data == null || data.isEmpty( ) ){
				this.ajaxResponse( 3 );
				return;
			}
			
			Byte isdefault = ( Byte ) data.get( "isdefault" );
			if( isdefault == 1  ){
				this.ajaxResponse( 4 );
				return;
			}
		}
		
		
		int count = baseService.countBySQL( "select count(*) as a from dstzadmin where groupid=:groupid", DataBaseUtils.getData( new String[]{
				"groupid"
		}, new Object[]{
				id
		} ) );
		
		if( count > 0 ){
			this.ajaxResponse( 1 );
			return; // 被引用
		}
		
		
		int del = baseService.deleteBySql( "dstzgroup", DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		if( del > 0 ){
			del = baseService.deleteBySql( "dstz_group_type", DataBaseUtils.getData( new String[]{
				"groupid"
			}, new Object[]{
					id
			} ) );
		}
		
		this.addLog( del, "admingroup", 1, "ID：" + id );
		
		this.ajaxResponse( del > 0 ? 0 : -1 );
		
	}
	
	public void setpurview( ){
		
		String nodes = getParameter( "nodes" );
		
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		if( nodes == null ){
			this.ajaxResponse( 1 );
			return;
		}
		
		String [] splitNodes = StringUtils.split( nodes, "," );
		
		if( splitNodes == null || splitNodes.length == 0 ){
			this.ajaxResponse( 1 );
			return;
		}
		
		Map< String, Object > data = baseService.queryForMap( "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid  and g.id=:id", DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		if( data == null || data.isEmpty( ) ){
			this.ajaxResponse( 3 );
			return;
		}else{
			Byte ismanager = ( Byte ) data.get( "ismanager" );  // 表示不是管理组,不可分配权限
			if( ismanager == 0 ){
				this.ajaxResponse( 2 );
				return;
			}
		}
		
		List< String  > sqls = new ArrayList< String >( splitNodes.length  );
		// 开始保存信息
		for( String node : splitNodes ){
			String sql = DataBaseUtils.getInsertSQL( "dstz_group_function", DataBaseUtils.getData( new String[]{ "functionid", "groupid"
			}, new Object[]{
					node, id
			} ) );
			sqls.add( sql );
		}
		// 删除所有的数据，然后再执行插入
		baseService.deleteBySql( "dstz_group_function",  DataBaseUtils.getData( new String[]{ "groupid"}, new Object[]{id } )  );
		
		int save = baseService.saveOrUpdateBatch( sqls );
		
		this.addLog( save, "admingroup", 1, "ID：" + id, "【分配权限】->" );
		
		this.ajaxResponse( save > 0 ? 0 : -1 );
		return;
	}
	
	public void purview( ){
		
		// 获取当前分组的权限
		List< Map< String, Object >> currentGroupFunctionList = getCurrentGroupFunction( );
		
		List< Map< String, Object >> parentList = getList( );
		List< Map< String, Object >> treeList = new ArrayList< Map< String, Object >> ( );
		treeList.add( getRootNodes( ) );
		
		for( Map< String, Object > parent : parentList ){
			Object id = parent.get( "id" );
			Object name = parent.get( "name" );
			Object description = parent.get( "description" );
			Object url = getRequest( ).getContextPath( ) + "/admin/function/functionAct!toedit.action?id=" + id;
			Integer parentid = ( Integer ) parent.get( "parentid" );
			if( parentid == 0 ){
				parentid = 99999999;
			}
			
			boolean checked = false;
			for( Map< String, Object > current : currentGroupFunctionList ){
				Object functionId = current.get( "functionid" );
				if( functionId.equals( id )){
					checked = true;
				}
			}
			
			treeList.add( getNodes( id, parentid, name + "【" + description + "】", url, false, checked ) );
		}
		this.ajaxResponse( JSONArray.fromObject( treeList ) );
		return;
	}
	
	
	public String topurview( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		
		if( validSaveOrUpdate > 0 ){
			alertMsg( "无法获取对应的数据信息！" );
			return "purview";
		}
		
		Map< String, Object > data = baseService.queryForMap( "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid  and g.id=:id", DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		if( data == null || data.isEmpty( ) ){
			alertMsg( "无法获取对应的数据信息！" );
		}else{
			Byte ismanager = Common.convert( data.get( "ismanager" ) );
			
			if( ismanager == 0 ){
				alertMsg( "该分组不属于系统管理组，不可分配权限！" );
			}
		}
		
		getRequest( ).setAttribute( "data", data ); // 设置到request中
		
		return "purview";
	}
	
	private List< Map< String, Object >> getCurrentGroupFunction( ){
		
		List< Map< String, Object >> list = baseService.queryForListByAll( "select * from dstz_group_function where groupid=:groupid ", DataBaseUtils.getData( new String[]{
				"groupid"
		}, new Object[]{
				id
		} ) );
		return list;
		
	}
	
	
	private Map< String, Object > getNodes( Object id, Object pId, Object name, Object url, boolean open, boolean checked ){
		return ActionUtils.getNodes( id, pId, name, url, open, checked, null );
	}
	
	private Map< String, Object > getRootNodes( ){
		return getNodes( 99999999, 0, "分配权限", "", true, false );
	}
	
	private List< Map< String, Object >> getList(  ){
		List< Map< String, Object >> list = baseService.queryForListByAll( "select * from dstz_function ", null );
		return list;
	}
	
	private int delete( int id ){
		
		return baseService.deleteBySql( "dstzgroup", DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
	}
	
	private int validSaveOrUpdate( int saveOrUpdate ){
		// 验证数据是否存在， 编辑或者删除的
		if( saveOrUpdate == 2 ){
			if( id == null || id == 0 ){
				return 3;
			}
			return 0;
		}
		
		if( ValidUtils.validLength( name, 1, 32 )){
			return 1;
		}
		
		int count = 0;
		
		if( saveOrUpdate == 0 ){
			count = dbValid( );
		}else if( saveOrUpdate == 1 ){
			if( id == null || id == 0 ){
				return 3;
			}
			if( !StringUtils.equals( name, oldname )){
				count = dbValid( );
			}
		}
		
		if( count > 0 ){
			return 2;
		}
		
		return count;
		
	}
	
	private int dbValid( ){
		String sql = "select count(*) as a from dstzgroup where name=:name";
		
		return baseService.countBySQL( sql, DataBaseUtils.getData( new String[]{
				"name"
		}, new Object[]{
				name
		} ) );
	}
	
	private static final long serialVersionUID = 1L;
	
	private Integer id;
	
	private String name;
	private String oldname;
	
	private Integer allowlogin;
	
	private Integer ismanager;
	
	private Integer level;
	
	private Integer isdefault;
	
	public String getName( ) {
		return name;
	}

	public void setName( String name ) {
		if( StringUtils.isNotBlank( name ) ){
			name = decode( name ); // 进行解码操作
		}
		this.name = name;
	}

	public Integer getAllowlogin( ) {
		return allowlogin;
	}

	public void setAllowlogin( Integer allowlogin ) {
		if( allowlogin == null ){
			allowlogin = 0;
		}
		this.allowlogin = allowlogin;
	}

	public Integer getIsmanager( ) {
		return ismanager;
	}

	public void setIsmanager( Integer ismanager ) {
		if( ismanager == null ){
			ismanager = 0;
		}
		this.ismanager = ismanager;
	}

	public String getOldname( ) {
		return oldname;
	}

	public void setOldname( String oldname ) {
		if( StringUtils.isNotBlank( oldname ) ){
			oldname = decode( oldname ); // 进行解码操作
		}
		this.oldname = oldname;
	}

	public Integer getId( ) {
		return id;
	}

	public void setId( Integer id ) {
		if( id == null ){
			id = 0;
		}
		this.id = id;
	}

	public Integer getLevel( ) {
		return level;
	}

	public void setLevel( Integer level ) {
		this.level = level;
	}

	public Integer getIsdefault( ) {
		if( isdefault == null ){
			isdefault = 0;
		}
		return isdefault;
	}

	public void setIsdefault( Integer isdefault ) {
		this.isdefault = isdefault;
	}
	
}
